<html>
  <head>
      <link rel="stylesheet" type="text/css" href="../Styles/style.css" />
  <?php
	 require_once("../Scripts/chartProcess.php");//obtains data from database
  ?>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
		
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(ClosePriceDrawChart);
	  google.setOnLoadCallback(VolumeDrawChart);
	  google.setOnLoadCallback(indicatorDrawChart);
	 //google.setOnLoadCallback(SMADrawChart);
	 //google.setOnLoadCallback(WMADrawChart);
	  //google.setOnLoadCallback(EMADrawChart);
	  //google.setOnLoadCallback(SARDrawChart);
	  //google.setOnLoadCallback(BollingerDrawChart);
	  //global variables
	 

	  var symbols =[];
	  var colours=[];
	  var startDate="";
	  var endDate="";


function addSymbol(){		
	  	symbol=document.getElementById("comparestock");
	  	if(symbol.value!="none"){
		symbol=document.getElementById("comparestock");
		symbols.push(symbol.value);
			//remove duplicate symbols
			symbols = symbols.filter(function(elem, pos, self) {
				return self.indexOf(elem) == pos;
			})
		
		
		if(sessionStorage['symbols']){
			var localsymbols=sessionStorage['symbols'].split(",");
			for(i=0;i<localsymbols.length;i++){
				symbols.push(localsymbols[i]);	
			}
			symbols = symbols.filter(function(elem, pos, self) {
			return self.indexOf(elem) == pos;
				})
				
			
		}
		
		window.sessionStorage.setItem("symbols", symbols);
		
		displaySymbols()
		}
		//Advanced chart symbol
		var advSymbol=document.getElementById("advSymbol")
		if(advSymbol.value!="none"){

		window.sessionStorage.setItem("advSymbol",advSymbol.value);
		
		}
		
			
		//refresh page if we have either of the symbols
		if(sessionStorage['symbols']||sessionStorage['advSymbol']){		
	window.location.href = "chart.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate']+ "&displays=" +sessionStorage['displays']+ "&advSymbol=" + sessionStorage['advSymbol']+ "&advStartDate="+ sessionStorage['advStartDate']+ "&advType="+sessionStorage["advType"]+ "&advEndDate="+ sessionStorage['advEndDate'];
		}
		
	  }

function processPercentage(){
var percentage=document.getElementById("percentage");
 if(percentage.checked==true){
	window.sessionStorage.setItem("percentage","true");	
} 

if(percentage.checked==false){
	window.sessionStorage.setItem("percentage","false");	
}
	window.location.href = "chart.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate']+ "&displays=" +sessionStorage['displays']+ "&advSymbol=" + sessionStorage['advSymbol']+ "&advStartDate="+ sessionStorage['advStartDate']+ "&advType="+sessionStorage["advType"]+ "&advEndDate="+ sessionStorage['advEndDate'];
}


function processType(){
var type= document.getElementById('Type');
if(type.value!="none"){
	if(sessionStorage["type"]){
		sessionStorage["type"]=type.value;	
	}
	else{
		window.sessionStorage.setItem("type",type.value);	
	}
}else{
	window.sessionStorage.setItem("type","Close");	
}
	window.location.href = "chart.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate']+ "&displays=" +sessionStorage['displays']+ "&advSymbol=" + sessionStorage['advSymbol']+ "&advStartDate="+ sessionStorage['advStartDate']+ "&advType="+sessionStorage["advType"]+ "&advEndDate="+ sessionStorage['advEndDate'];

}
function advProcessType(){
var type= document.getElementById('advType');
if(type.value!="none"){
	if(sessionStorage["advType"]){
		sessionStorage["advType"]=type.value;	
	}
	else{
		window.sessionStorage.setItem("advType",type.value);	
	}
}else{
	window.sessionStorage.setItem("advType","Close");	
}
	window.location.href = "chart.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate']+ "&displays=" +sessionStorage['displays']+ "&advSymbol=" + sessionStorage['advSymbol']+ "&advStartDate="+ sessionStorage['advStartDate']+ "&advType="+sessionStorage["advType"]+ "&advEndDate="+ sessionStorage['advEndDate'];

}
	  
function processDate(){
		startDate=document.getElementById("startDate").value;
		endDate=document.getElementById("endDate").value;
		
		window.sessionStorage.setItem("startDate", startDate);
		window.sessionStorage.setItem("endDate", endDate);
			
		//refresh page if we have the 
		if(sessionStorage['startDate']&&sessionStorage['endDate']){		
	window.location.href = "chart.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate']+ "&displays=" +sessionStorage['displays']+ "&advSymbol=" + sessionStorage['advSymbol']+ "&advStartDate="+ sessionStorage['advStartDate']+ "&advType="+sessionStorage["advType"]+ "&advEndDate="+ sessionStorage['advEndDate'];
		}
		  
	  }
function processAdvDate(){
		//advanced start and end date
		var advStartDate=document.getElementById("advStartDate").value;
		var advEndDate=document.getElementById("advEndDate").value;
		
		window.sessionStorage.setItem("advStartDate", advStartDate);
		window.sessionStorage.setItem("advEndDate", advEndDate);
		
		if(sessionStorage['advStartDate']&&sessionStorage['advEndDate']){		
	window.location.href = "chart.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate']+ "&displays=" +sessionStorage['displays']+ "&advSymbol=" + sessionStorage['advSymbol']+ "&advStartDate="+ sessionStorage['advStartDate']+ "&advType="+sessionStorage["advType"]+ "&advEndDate="+ sessionStorage['advEndDate'];
		}
		  
		  
	  }
	  
function ClosePriceDrawChart() {//Close Price

		//ensure we have all of the required variables
		if(sessionStorage['startDate']&&sessionStorage['endDate']&&sessionStorage['symbols']&&sessionStorage['type']){
		//set value of dates from local storage.	
		document.getElementById("closePriceChart_div").style.display="block";//show the chart div
		
	  	  
  var time = <?php echo json_encode($dates); ?>;
  var Symboldata=<?php echo json_encode($symbolArray); ?>;;
 
  
  console.log("dates");
  console.log(time);
  console.log("Symboldata");
  console.log(Symboldata);

  var data = new google.visualization.DataTable();
  data.addColumn('date', 'days');
  
  	//add column for each symbol
	
	var localsymbols=sessionStorage['symbols'].split(",");
	console.log("symbols: " +localsymbols)
	
	for( i=0; i< localsymbols.length;i++){
		data.addColumn('number',localsymbols[i]);	
		
	}
	  
	//for the length of the Symbol data array
		
	console.log("time: "+time.length);	
  for(i = 0; i < time.length; i++){
	  
	  //add row based on count of symbols
	var row=[];
	var index=0;
	
	var date= time[i].split("-");
	row.push(new Date(date[0], date[1]-1,date[2]));
	
	for(thing in localsymbols){
	row.push(Number(Symboldata[index][i]));
	index+=1;
	}
	
    data.addRow(row);
	console.log("row");
	console.log(row);
	
  }
		}
  console.log(data);
  		var Min=Math.min.apply(Math, Symboldata);
		var Max=Math.max.apply(Math, Symboldata);
		console.log(Min);
		console.log(Max);
        var options = {
          title: 'Compare Stock Close Prices',
          hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
          vAxis: {title: 'End price', minValue: Min},
		  explorer: {axis:'both',
          maxZoomin:0.25,
          keepInBounds: true
		  }
        };
		
        var chart = new google.visualization.AreaChart(document.getElementById('closePriceChart_div'));
        chart.draw(data, options);
      
	  }
  
function VolumeDrawChart() {//Volume
	
		//ensure we have all of the required variables
		if(sessionStorage['startDate']&&sessionStorage['endDate']&&sessionStorage['symbols']&&sessionStorage['type']){
		document.getElementById("volumeChart_div").style.display="block";//show the chart div
		
		  // Create and populate the data table.
	  
  var time = <?php echo json_encode($dates); ?>;
  var volumeData=<?php echo json_encode($volumeArray); ?>;
 

  var data = new google.visualization.DataTable();
  data.addColumn('date', 'days');
  
  	//add column for each symbol
	
	var localsymbols=sessionStorage['symbols'].split(",");

	for( i=0; i< localsymbols.length;i++){
		data.addColumn('number',localsymbols[i]);	
		
	}
	  
	//for the length of the Symbol data array
		
	console.log("time: "+time.length);	
  for(i = 0; i < time.length; i++){
	  
	  //add row based on count of symbols
	var row=[];
	var index=0;
	var date= time[i].split("-");
	row.push(new Date(date[0], date[1]-1,date[2]));
	
	
	for(thing in localsymbols){
	row.push(Number(volumeData[index][i]));
	index+=1;
	}
	
    data.addRow(row);

	
  }
		}
		var Min=Math.min.apply(Math, volumeData);
		var Max=Math.max.apply(Math, volumeData);
		console.log(Min);
		console.log(Max);
        var options = {
          title: 'Compare Stock Volume',
          hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
          vAxis: {title: 'Volume', minValue: Min},
		  explorer: {axis:'both',
          maxZoomin:0.25,
          keepInBounds: true
    	}
        };
		
        var chart = new google.visualization.AreaChart(document.getElementById('volumeChart_div'));
        chart.draw(data, options);
      
	  }
	  
function cookies(){
		  window.sessionStorage.clear();
	  }
	  
function getRandomColor() {
	var colours= ['#3366CC','#DC3912','#FF9900','#109618','#990099','#0099C6','#66AA00','#B82E2E','#316395','#994499','#22AA99','#AAAA11','#6633CC',
	'#E67300','#8B0707','#329262','#5574A6'];
	var i= Math.floor((Math.random() * 16) + 0);
    return colours[i];
}
	  
function SMADrawChart(){
				if(sessionStorage['startDate']&&sessionStorage['endDate']&&sessionStorage['symbols']){

				//set the value of displays from local variables
				if(sessionStorage['displays']){			
					var localdisplays=sessionStorage['displays'].split(",");
						for(i=0;i<localdisplays.length;i++){
							var splitdisplay=localdisplays[i].split("/");
							if(splitdisplay[0]=="SMA"){
								//draw the chart	
							  document.getElementById("SMAChart_div").style.display="block";//show the chart div
									
									  // Create and populate the data table.
								  
							  var time = <?php echo json_encode($dates); ?>;
							  var smaData=<?php echo json_encode($smaArray); ?>;
							  console.log("SMAdata");
  							  console.log(smaData);
							 
							
							  var data = new google.visualization.DataTable();
							  data.addColumn('string', 'days');
							  
								//add column for each symbol
								
								var localsymbols=sessionStorage['symbols'].split(",");
							
								for( i=0; i< localsymbols.length;i++){
									data.addColumn('number',localsymbols[i]);	
									
								}
								  
								//for the length of the Symbol data array
									
								console.log("time: "+time.length);	
							  for(i = 0; i < time.length; i++){
								  
								  //add row based on count of symbols
								var row=[];
								var index=0;
								
								row.push(time[i]);
								
								for(thing in localsymbols){
								row.push(Number(smaData[index][i]));
								index+=1;
								}
								
								data.addRow(row);
							
								
							  }
									}
							
									var options = {
									  title: 'Compare Stock SMA',
									  hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
									  vAxis: {title: 'SMA', minValue: 0}
									};
									
									var chart = new google.visualization.AreaChart(document.getElementById('SMAChart_div'));
									chart.draw(data, options);
								
								
								
							}
			
						}
				}  
		  
		  
	  }
	  
function WMADrawChart(){
				if(sessionStorage['startDate']&&sessionStorage['endDate']&&sessionStorage['symbols']){

				//set the value of displays from local variables
				if(sessionStorage['displays']){			
					var localdisplays=sessionStorage['displays'].split(",");
						for(i=0;i<localdisplays.length;i++){
							var splitdisplay=localdisplays[i].split("/");
							if(splitdisplay[0]=="WMA"){
								//draw the chart	
							  document.getElementById("WMAChart_div").style.display="block";//show the chart div
									
									  // Create and populate the data table.
								  
							  var time = <?php echo json_encode($dates); ?>;
							  var wmaData=<?php echo json_encode($wmaArray); ?>;
							  console.log("WMAdata");
  							  console.log(wmaData);
							 
							
							  var data = new google.visualization.DataTable();
							  data.addColumn('string', 'days');
							  
								//add column for each symbol
								
								var localsymbols=sessionStorage['symbols'].split(",");
							
								for( i=0; i< localsymbols.length;i++){
									data.addColumn('number',localsymbols[i]);	
									
								}
								  
								//for the length of the Symbol data array
									
								console.log("time: "+time.length);	
							  for(i = 0; i < time.length; i++){
								  
								  //add row based on count of symbols
								var row=[];
								var index=0;
								
								row.push(time[i]);
								
								for(thing in localsymbols){
								row.push(Number(wmaData[index][i]));
								index+=1;
								}
								
								data.addRow(row);
							
								
							  }
									}
							
									var options = {
									  title: 'Compare Stock WMA',
									  hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
									  vAxis: {title: 'WMA', minValue: 0}
									};
									
									var chart = new google.visualization.AreaChart(document.getElementById('WMAChart_div'));
									chart.draw(data, options);
								
								
								
							}
			
						}
				}  
		  
		  
	  }	 
	  
function EMADrawChart(){
				if(sessionStorage['startDate']&&sessionStorage['endDate']&&sessionStorage['symbols']){

				//set the value of displays from local variables
				if(sessionStorage['displays']){			
					var localdisplays=sessionStorage['displays'].split(",");
						for(i=0;i<localdisplays.length;i++){
							var splitdisplay=localdisplays[i].split("/");
							if(splitdisplay[0]=="EMA"){
								//draw the chart	
							  document.getElementById("EMAChart_div").style.display="block";//show the chart div
									
									  // Create and populate the data table.
								  
							  var time = <?php echo json_encode($dates); ?>;
							  var emaData=<?php echo json_encode($wmaArray); ?>;
							  console.log("EMAdata");
  							  console.log(emaData);
							 
							
							  var data = new google.visualization.DataTable();
							  data.addColumn('string', 'days');
							  
								//add column for each symbol
								
								var localsymbols=sessionStorage['symbols'].split(",");
							
								for( i=0; i< localsymbols.length;i++){
									data.addColumn('number',localsymbols[i]);	
									
								}
								  
								//for the length of the Symbol data array
									
								console.log("time: "+time.length);	
							  for(i = 0; i < time.length; i++){
								  
								  //add row based on count of symbols
								var row=[];
								var index=0;
								
								row.push(time[i]);
								
								for(thing in localsymbols){
								row.push(Number(emaData[index][i]));
								index+=1;
								}
								
								data.addRow(row);
							
								
							  }
									}
							
									var options = {
									  title: 'Compare Stock EMA',
									  hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
									  vAxis: {title: 'EMA', minValue: 0}
									};
									
									var chart = new google.visualization.AreaChart(document.getElementById('EMAChart_div'));
									chart.draw(data, options);
								
								
								
							}
			
						}
				}  
		  
		  
	  }	 
	  
function indicatorDrawChart() {//Indicator Price
		
		//ensure we have all of the required variables
		
		if(sessionStorage['advStartDate']&&sessionStorage['advEndDate']&&sessionStorage['advSymbol']&&sessionStorage['displays']&&sessionStorage['advType']){


		document.getElementById("indicatorChart_div").style.display="block";//show the chart div

			var localdisplays=sessionStorage['displays'].split(",");

		  // Create and populate the data table.
		  var time = <?php echo json_encode($advDates); ?>;
  		  var Symboldata=<?php echo json_encode($advSymbolArray); ?>;;
		  
		  console.log("timess");
		  console.log(time);

			
			var smaData=<?php echo json_encode($smaArray); ?>;
			console.log("SMA");
			console.log(smaData);


  var data = new google.visualization.DataTable();
  data.addColumn('date', 'days');
  colours.push(getRandomColor());
  

		data.addColumn('number',sessionStorage['advSymbol']);	
		
		//add a column for each displays
		for(i=0;i<localdisplays.length;i++){
			var splitdisplay=localdisplays[i].split("/");
			if(splitdisplay.length>2&&splitdisplay[0]!="SAR"&&splitdisplay[0]!="Bollinger"){
				for(x=1;x<splitdisplay.length;x++){
					
					data.addColumn('number',splitdisplay[0]+"/"+splitdisplay[x]);
					colours.push(getRandomColor());
				
				}
				
				
				
			}else if(splitdisplay[0]=="Bollinger"){
				data.addColumn('number',"BbandUpper");
				colours.push('#3B3EAC');
				data.addColumn('number',"BbandMiddle");
				colours.push('#DD4477');
				data.addColumn('number',"BbandLower");
				colours.push('#3B3EAC');
				
			}
			else{
				data.addColumn('number',localdisplays[i]);	
				colours.push(getRandomColor());
			}
		}
		
		
			
		
	  
	//for the length of the Symbol data array
	console.log("time: "+time.length);	
  for(i = 0; i < time.length; i++){
	  
	  //add row based on count of symbols
	var row=[];
	
	
	
	var date= time[i].split("-");

	row.push(new Date(date[0], date[1]-1,date[2]));

	row.push(Number(Symboldata[i]));
	
	//add a column for each displays
	for(x=0;x<localdisplays.length;x++){
		var splitdisplay=localdisplays[x].split("/");
		
		if(splitdisplay[0]=="SMA"){
			var smaData=<?php echo json_encode($smaArray); ?>;
			if(splitdisplay.length>2){
				for(j=1;j<splitdisplay.length;j++){
					row.push(Number(smaData[j-1][i+(splitdisplay[j]-1)]));
				}
				}else{
			
			//add SMA data to row	
			
			console.log("SMA");
			console.log(smaData);
				row.push(Number(smaData[0][i+(splitdisplay[1]-1)]));
				}
		}
		if(splitdisplay[0]=="EMA"){
			var emaData=<?php echo json_encode($emaArray); ?>;
			if(splitdisplay.length>2){
				for(j=1;j<splitdisplay.length;j++){
					row.push(Number(emaData[j-1][i+(splitdisplay[j]-1)]));
				}
				}else{
			
			//add EMA data to row	
			
			console.log("EMA");
			console.log(emaData);
				row.push(Number(emaData[0][i+(splitdisplay[1]-1)]));
				}
		}
		if(splitdisplay[0]=="WMA"){
			var wmaData=<?php echo json_encode($wmaArray); ?>;
			if(splitdisplay.length>2){
				for(j=1;j<splitdisplay.length;j++){
					row.push(Number(wmaData[j-1][i+(splitdisplay[j]-1)]));
					
				}
				}else{
			
			//add WMA data to row	
			
			//console.log("SMA");
			//console.log(smaData);
				row.push(Number(wmaData[0][i+(splitdisplay[1]-1)]));
				}
		}
		
		if(splitdisplay[0]=="SAR"){
			var sarData=<?php echo json_encode($sarArray); ?>;
			console.log("SAR");
			console.log(sarData);
			row.push(Number(sarData[0][i+1]));
				
		}
		if(splitdisplay[0]=="Bollinger"){
			var bollingerData=<?php echo json_encode($bollingerArray); ?>;
			console.log(bollingerData);
			row.push(Number(bollingerData[0][0][i+(splitdisplay[1]-1)]));
			row.push(Number(bollingerData[0][1][i+(splitdisplay[1]-1)]));
			row.push(Number(bollingerData[0][2][i+(splitdisplay[1]-1)]));
				
		}
		
		
				
	}

	
	
    data.addRow(row);

	
  
		}
		
		var Min=Math.min.apply(Math, Symboldata);
		var Max=Math.max.apply(Math, Symboldata);
		console.log(Min);
		console.log(Max);
        var options = {
          title: 'Compare '+sessionStorage['advSymbol']+' Prices With Indicators',
		  
						  
          hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
		  
          vAxis: {title: 'Prices', minValue: Min, maxValue: Max},
			explorer: {axis:'both',
        	maxZoomin:0.25,
        	keepInBounds: true
    	},
		  
		  colors: colours
		  
		  
        };
		
        var chart = new google.visualization.LineChart(document.getElementById('indicatorChart_div'));
        chart.draw(data, options);
      

	  
	  
}
}  
function ProcessDisplay(){
			//Check which boxes are checked:
			var SMA =document.getElementById('SMA');
			var WMA =document.getElementById('WMA');
			var EMA =document.getElementById('EMA');
			var SAR =document.getElementById('SAR');
			var Bollinger =document.getElementById('Bollinger');
			
			//get the time period
			var SMAn =document.getElementById('SMAn');
			var WMAn =document.getElementById('WMAn');
			var EMAn =document.getElementById('EMAn');
			var SARn =document.getElementById('SARn');
			var Bollingern =document.getElementById('Bollingern');
			
			//Create an array of checked boxes to be displayed.
			var displays =[];
			
			//check if displays array is already in local cache
			
			if(sessionStorage['displays']){
				//add local storage displays to the displays array
				var localdisplays=sessionStorage['displays'].split(",");
				for(i=0;i<localdisplays.length;i++){
					displays.push(localdisplays[i]);	
				
				}
			}
		  
			if(SMA.checked==true){
				//ensure that their is only one SMA in the dispalys array
				for(var i=0;i<displays.length;i++){
					var displaycheck = displays[i].split("/");
					if(displaycheck[0]=="SMA"){
						displays.splice(i,1);		
					}
				}
				
				//var validate =/\d+\//;
				
				//alert(validate.test('10'));
				//if(validate.test(SMAn.value)==true){
					//CHECK IF VALID
					if(SMAn.value==""){
						displays.push("SMA/20");
					}else{
					displays.push("SMA/"+SMAn.value);
					}
				//}else{
					
					//displays.push("SMA/20");	
				//}
	
			}else{
				if(displays.indexOf("SMA/"+SMAn.value)>-1){
					displays.splice(displays.indexOf("SMA/"+SMAn.value), 1);//remove from displays array
				}
				
					
			}

			if(WMA.checked==true){
				//ensure that their is only one WMA in the dispalys array
				for(var i=0;i<displays.length;i++){
					var displaycheck = displays[i].split("/");
					if(displaycheck[0]=="WMA"){
						displays.splice(i,1);		
					}
				}
				//if(WMAn.value>1){
					if(WMAn.value==""){
						displays.push("WMA/20");
					}else{
					displays.push("WMA/"+WMAn.value);
					}
				//}else{
					//displays.push("WMA/20");	
				//}
				
			}else{
				if(displays.indexOf("WMA/"+WMAn.value)>-1){
					displays.splice(displays.indexOf("WMA/"+WMAn.value), 1);//remove from displays array
				}
				
			}
			
			if(EMA.checked==true){
				//ensure that their is only one EMA in the dispalys array
				for(var i=0;i<displays.length;i++){
					var displaycheck = displays[i].split("/");
					if(displaycheck[0]=="EMA"){
						displays.splice(i,1);		
					}
				}
				//if(EMAn.value>1){
					if(EMAn.value==""){
						displays.push("EMA/20");
					}else{
					displays.push("EMA/"+EMAn.value);
					}
				//}else{
					//displays.push("EMA/20");	
				//}
				
			}else{
				if(displays.indexOf("EMA/"+EMAn.value)>-1){
					displays.splice(displays.indexOf("EMA/"+EMAn.value), 1);//remove from displays array
				}
				
			}
			
			if(SAR.checked==true){
				//ensure that their is only one SAR in the dispalys array
				for(var i=0;i<displays.length;i++){
					var displaycheck = displays[i].split("/");
					if(displaycheck[0]=="SAR"){
						displays.splice(i,1);		
					}
				}
				//if(SARn.value>1){
					if(SARn.value==""){
						displays.push("SAR/0.02/0.2");
					}else{
					displays.push("SAR/"+SARn.value);
					}
				//}else{
				//	displays.push("SAR/20");	
				//}
				
			}else{
				if(displays.indexOf("SAR/"+SARn.value)>-1){
					displays.splice(displays.indexOf("SAR/"+SARn.value), 1);//remove from displays array
				}
				
			}
			
			if(Bollinger.checked==true){
				//ensure that their is only one Bollinger in the dispalys array
				for(var i=0;i<displays.length;i++){
					var displaycheck = displays[i].split("/");
					if(displaycheck[0]=="Bollinger"){
						displays.splice(i,1);		
					}
				}
				//if(Bollingern.value>1){
					if(Bollingern.value==""){
						displays.push("Bollinger/20/2");
					}else{
					displays.push("Bollinger/"+Bollingern.value);
					}
				//}else{
					//displays.push("Bollinger/20");	
				//}
				
			}else{
				if(displays.indexOf("Bollinger/"+Bollingern.value)>-1){
					displays.splice(displays.indexOf("Bollinger/"+Bollingern.value), 1);//remove from displays array
				}
				
			}
			

				//remove duplicates if any
				displays = displays.filter(function(elem, pos, self) {
				return self.indexOf(elem) == pos;
				});
				
			
			
			
			//Add Array of displays to local storage
			window.sessionStorage.setItem("displays", displays);
			
			//Refresh page to run the php and obtain the data for the displays
		if(sessionStorage['displays']){		
	window.location.href = "chart.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate']+ "&displays=" +sessionStorage['displays']+ "&advSymbol=" + sessionStorage['advSymbol']+ "&advStartDate="+ sessionStorage['advStartDate']+ "&advType="+sessionStorage["advType"]+ "&advEndDate="+ sessionStorage['advEndDate'];
		}
			
		  
		
	  }

function showInfo(sender){
	var show=document.getElementById("info_div")
	if( show.style.display=="none"){
		show.style.display="block"	
	}else{
		show.style.display="none";	
	}
	var info= document.getElementById("infoText");
	var textExample= document.getElementById("exampleText");
	
	info.innerHTML="YOLO";
	switch(sender){
		case "SMA":
			info.innerHTML="<strong>Description:</strong> Moving averages smooth the price data to form a trend following indicator. A simple moving average is formed by computing the average price of a security over a specific number of periods. Old data is dropped as new data comes available. This causes the average to move along the time scale.";
			textExample.innerHTML="<strong>How to:</strong> Calculate the SMA by filling in the provided text box like: '20/50/100'. Where the '/' adds another line to be plotted."
			break;
		case "EMA":
			info.innerHTML="<strong>Description:</strong> Exponential moving average is a type of moving average that is similar to a simple moving average, except that more weight is given to the latest data. The weighting for each older data point decreases exponentially, never reaching zero. It reduces the lag by applying more weight to recent prices.";
			textExample.innerHTML="<strong>How to:</strong> Calculate the EMA by filling in the provided text box like: '20/50/100'. Where the '/' adds another line to be plotted."
			break;
		case "WMA":
			info.innerHTML="<strong>Description:</strong> The Weighted Moving Average (WMA) finds the average price of a security over a set number of periods. It gives more weight to the more recent prices, relative to older prices, in an attempt to reduce the lag associated with moving averages, in general. This is calculated by multiplying each of the previous interval's data by a weight based on the period length in the WMA. Each price is multiplied by a factor, with the current price having the highest factor and each price after that having a factor of the prior price less one.";
			textExample.innerHTML="<strong>How to:</strong> Calculate the WMA by filling in the provided text box like: '20/50/100'. Where the '/' adds another line to be plotted."
			break;
		case "SAR":
			info.innerHTML="<strong>Description:</strong> SAR stands for 'stop and reverse', which is the actual indicator used in the system. SAR trails price as the trend extends over time. The indicator is below prices when prices are rising and above prices when prices are falling. In this regard, the indicator stops and reverses when the price trend reverses and breaks above or below the indicator.";
			textExample.innerHTML="<strong>How to:</strong> Calculate the SAR by filling in the provided text box like: 'x/y', Where the 'x' is the acceleration factor and 'y' is the Maximum."
			break;
		case "Bollinger":
			info.innerHTML="<strong>Description:</strong> Bollinger Bands are volatility bands placed above and below a moving average. The Bollinger Band includes 3 lines: the upper band, lower band, and the centerline. The centerline is simply the moving average, and the upper and lower bands are, respectively, the center line plus/minus twice the standard deviation. ";
			textExample.innerHTML="<strong>How to:</strong> Calculate the Bollinger bands by filling in the provided text box like: 'x/y', Where the 'x' is the SMA days and 'y' is the standard deviation."
			break;
				
	}
	
}

    </script>
  </head>
  <body>
  				<h2>Compare Different stock prices between different symbols</h2>
  	              <label for="textfield2">Add Symbol:</label>
                  <select id='comparestock' name='Symbol'>
                  <option value='none'>Choose symbols</option>
              <?php
				$result = mysqli_query($con,"SELECT * FROM  `company info`");

				while($row = mysqli_fetch_array($result)) {
					
    				echo "<option value='$row[Symbol]'>" . $row['Symbol'] . "</option>";

				}
				
				echo "</select>";
				//mysqli_close($con);
			  
			  //generate a button for each symbol to remove 	

			  ?>
             
            <button onClick="addSymbol()">Add</button>
            <br/>
            <span id="holdSymbols">&nbsp;</span>
            <br/>
              <label>Start date</label>
              <input type="date" id="startDate" onChange="processDate()">
              <label>End date</label>
              <input type="date" id="endDate" onChange="processDate()">
              <label>Type</label>
              <select id='Type' name='Type' onChange="processType()">
              <option value='none'>Choose type</option>
              <option value='Close'>Close</option>
              <option value='High'>High</option>
              <option value='Low'>Low</option>
              <option value='Open'>Open</option>
              </select>
              <input type="checkbox" name="percentage" id="percentage" value="percentage" onChange="processPercentage()">Compare %
              <br>
              <h2>Compare Stock indicators with only one symbol</h2>
              
              <label for="textfield2">Add Symbol:</label>
              <select id='advSymbol' name='advSymbol' onChange="addSymbol()">
              <option value='none'>Choose symbol</option>
              <?php
				$result = mysqli_query($con,"SELECT * FROM  `company info`");


				

				while($row = mysqli_fetch_array($result)) {
					
    				echo "<option value='$row[Symbol]'>" . $row['Symbol'] . "</option>";

				}
				
				echo "</select>";
				//mysqli_close($con);
			  
			  //generate a button for each symbol to remove 	

			  ?>
              <label>Start date</label>
              <input type="date" id="advStartDate" onChange="processAdvDate()">
              <label>End date</label>
              <input type="date" id="advEndDate" onChange="processAdvDate()">
              <label>Type</label>
              <select id='advType' name='advType' onChange="advProcessType()">
              <option value='none'>Choose type</option>
              <option value='Close'>Close</option>
              <option value='High'>High</option>
              <option value='Low'>Low</option>
              <option value='Open'>Open</option>
              </select>
              
              <br>
              <label>Display:</label>
              <input type="checkbox"  name="SMA" id="SMA" value="SMA" onChange="ProcessDisplay()">SMA<input type="button" class="inf" id="SMAi" value="info" onClick="showInfo('SMA')">             								 			  <input type="text" name="SMAn" id="SMAn" value="" size="4" onChange="ProcessDisplay()">
              <input type="checkbox" name="WMA" id="WMA" value="WMA" onChange="ProcessDisplay()">WMA<input type="button" class="inf" id="WMAi" value="info" onClick="showInfo('WMA')">  
              <input type="text" name="WMAn" id="WMAn" value="" size="4" onChange="ProcessDisplay()">
              <input type="checkbox" name="EMA" id="EMA" value="EMA" onChange="ProcessDisplay()">EMA<input type="button" class="inf" id="EMAi" value="info" onClick="showInfo('EMA')"> 
              <input type="text" name="EMAn" id="EMAn" value="" size="4" onChange="ProcessDisplay()">
              <input type="checkbox" name="SAR" id="SAR" value="SAR" onChange="ProcessDisplay()">SAR<input type="button" class="inf" id="SARi" value="info" onClick="showInfo('SAR')"> 
              <input type="text" name="SARn" id="SARn" value="" size="4" onChange="ProcessDisplay()">
              <input type="checkbox" name="Bollinger" id="Bollinger" value="Bollinger" onChange="ProcessDisplay()">Bollinger<input type="button" class="inf" id="Bollingeri" value="info" onClick="showInfo('Bollinger')"> 
              <input type="text" name="Bollingern" id="Bollingern" value="" size="4" onChange="ProcessDisplay()">
              <button onClick="cookies()">Cookies</button>    
            
              </form>
             <div id="info_div" style="width: 900px; height: 120px; background-color:#CCC; display:none;">
             <label id="infoText" value="YOLO"></label>
             <label id="exampleText" value="YOLO"></label></div>
            <div id="closePriceChart_div" style="width: 900px; height: 250px; display:none;"></div><!--Close price Div-->
            <div id="volumeChart_div" style="width: 900px; height: 250px; display:none;"></div><!--Volume Div-->
            <div id="indicatorChart_div" style="width: 900px; height: 300px; display:none;"></div><!--SMA Div-->
            <div id="SMAChart_div" style="width: 900px; height: 250px; display:none;"></div><!--SMA Div-->
            <div id="WMAChart_div" style="width: 900px; height: 250px; display:none;"></div><!--SMA Div-->
            <div id="EMAChart_div" style="width: 900px; height: 250px; display:none;"></div><!--SMA Div-->
            <div id="SARChart_div" style="width: 900px; height: 250px; display:none;"></div><!--SMA Div-->
            <div id="BollingerChart_div" style="width: 900px; height: 250px; display:none;"></div><!--SMA Div-->
            
            
            
            
            <script type="text/javascript">
			function deleteSymbol(name){
				//find the symbol to delete in local symbols
				var localsymbols=sessionStorage['symbols'].split(",");
				
				//find index of symbol to be deleted
				var index = localsymbols.indexOf(name);
				//delete element at index
				localsymbols.splice(index, 1);
				
				//reset local storage of symbols
				window.sessionStorage.setItem("symbols", localsymbols);
				if(sessionStorage['symbols']==""){
	window.location.href = "chart.php?symbols=" + sessionStorage['symbols']+ "&type="+sessionStorage["type"]+ "&percentage="+sessionStorage["percentage"]+ "&endDate=" + sessionStorage['endDate']+ "&startDate=" + sessionStorage['startDate']+ "&displays=" +sessionStorage['displays']+ "&advSymbol=" + sessionStorage['advSymbol']+ "&advStartDate="+ sessionStorage['advStartDate']+ "&advType="+sessionStorage["advType"]+ "&advEndDate="+ sessionStorage['advEndDate'];
					
					
				}else{
				displaySymbols()
				drawChart()
				}
				
				
					
			}
			function displaySymbols(){
				
			if(sessionStorage['symbols']){
				
				//foreach symbol added create html button
				
				var localsymbols=sessionStorage['symbols'].split(",");
				var holdSymbols = document.getElementById("holdSymbols");	
				
				while (holdSymbols.firstChild) {
					holdSymbols.removeChild(holdSymbols.firstChild);
				}
						
				for( i=0; i< localsymbols.length;i++){
				var element = document.createElement("input");	
				
				element.setAttribute("type", "button");
				element.setAttribute("value", "remove,"+localsymbols[i]);
				element.setAttribute("name", localsymbols[i]);
				element.setAttribute("onClick", "deleteSymbol(this.name)");
				
				    
 				console.log(element);
				//Append the element in page (in span).
				
				holdSymbols.appendChild(element);
				
				}
				
 
			}  
			}
			displaySymbols()
		//display all the things!	
		if(sessionStorage['displays']){
		  
				//set localdisplays now so we can use it again
					
			var localdisplays=sessionStorage['displays'].split(",");
				for(i=0;i<localdisplays.length;i++){
					var splitdisplay=localdisplays[i].split("/");
					if(splitdisplay.length>2){
						var type=splitdisplay[0];
						splitdisplay.splice(0,1);
					document.getElementById(type).setAttribute("checked", true);	
					var localdisplay=splitdisplay.join();
					
					
					localdisplay=localdisplay.replace(/,/gi,'/');//replace , with /
					
					document.getElementById(type+"n").setAttribute("value", localdisplay);
						
					}else{
					document.getElementById(splitdisplay[0]).setAttribute("checked", true);	
					document.getElementById(splitdisplay[0]+"n").setAttribute("value", splitdisplay[1]);
					}
					
	
				}  
		  
	  }
	  
	  	if(sessionStorage['advStartDate']){
			document.getElementById("advStartDate").setAttribute("value", sessionStorage['advStartDate']);
			
		}
		if(sessionStorage['advEndDate']){
			document.getElementById("advEndDate").setAttribute("value", sessionStorage['advEndDate']);
			
		}
		if(sessionStorage['advSymbol']){
			var advSymbol= document.getElementById("advSymbol");
			advSymbol.value=sessionStorage["advSymbol"];
		
			
		}
		if(sessionStorage['startDate']){
			document.getElementById("startDate").setAttribute("value", sessionStorage['startDate']);
			
		}
		if(sessionStorage['endDate']){
			document.getElementById("endDate").setAttribute("value", sessionStorage['endDate']);
		}
		if(sessionStorage["type"]){
			
			var type=document.getElementById("Type");
			type.value=sessionStorage["type"];	
		}
		if(sessionStorage["advType"]){
			
			var type=document.getElementById("advType");
			type.value=sessionStorage["advType"];	
		}
		
		if(sessionStorage["percentage"]){
			if(sessionStorage["percentage"]=="true"){
				document.getElementById("percentage").setAttribute("checked", true);
			}
		}
		
			 

		
		
	  
			</script>  

</body>
  </body>
</html>

  